package com.lt.interactive.wechat.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lt.bcra.exception.BaseException;
import com.lt.bcra.result.ResponseEnum;
import com.lt.bcra.result.ResultData;
import com.lt.interactive.wechat.entity.BcraPersonalInfo;
import com.lt.interactive.wechat.mapper.BcraPersonalInfoMapper;
import com.lt.interactive.wechat.service.BcraPersonalInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 用户信息登录注册表 服务实现类
 * </p>
 *
 * @author LuoTian
 * @since 2022-06-11
 */
@Service
public class BcraPersonalInfoServiceImpl extends ServiceImpl<BcraPersonalInfoMapper, BcraPersonalInfo> implements BcraPersonalInfoService {

    @Autowired
    private BcraPersonalInfoMapper bcraPersonalInfoMapper;


    @Override
    public ResultData registerUser(BcraPersonalInfo bcraPersonalInfo) {
        bcraPersonalInfo.setRole("user");
        String phone = bcraPersonalInfo.getPhone();

        QueryWrapper<BcraPersonalInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        BcraPersonalInfo selectOne = bcraPersonalInfoMapper.selectOne(queryWrapper);

        if (selectOne != null) {
            throw new BaseException(ResponseEnum.MOBILE_SAME_ERROR);
        }

        int ok = bcraPersonalInfoMapper.insert(bcraPersonalInfo);
        if (ok != 1) {
            throw new BaseException(ResponseEnum.CREATE_DATA_ERROR);
        }
        return ResultData.getResult(ok);
    }

    @Override
    public BcraPersonalInfo selectWxInfoOpenId(String openid) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("open_id",openid);
        BcraPersonalInfo bcraPersonalInfo = bcraPersonalInfoMapper.selectOne(queryWrapper);
        return bcraPersonalInfo;
    }

    @Override
    public ResultData bindWechat(Integer id,String openid,String wechat) {

        String status = bcraPersonalInfoMapper.selectById(id).getStatus();

        UpdateWrapper<BcraPersonalInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);

        updateWrapper.set(status.equals("activation"), "open_id", openid);
        updateWrapper.set(status.equals("activation"), "wechat", wechat);

        int update = bcraPersonalInfoMapper.update(null, updateWrapper);

        if (update != 1) {
            throw new BaseException(ResponseEnum.WEIXIN_BIND_ERROR); //绑定异常
        }
        return ResultData.getResult(update);

    }
}
